package com.hndzyu.yd.my;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.R;
import com.hndzyu.yd.SplashActivity;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.bean.WxLoginBean;
import com.hndzyu.yd.ui.LoginActivity;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.DataCleanManager;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.SharedPreferencesUtils;
import com.hndzyu.yd.widget.ExitDialog;
import com.tencent.bugly.beta.Beta;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by zz9527 on 2018/11/7.
 */
public class SettingActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ImmersionBar.with(this).statusBarColor(R.color.them)
                .fitsSystemWindows(true).init();
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //清除缓存
        findViewById(R.id.qingchuhuancun).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ExitDialog mExitDialog = new ExitDialog(SettingActivity.this);
                mExitDialog.setExitListener(new ExitDialog.ExitListener() {
                    @Override
                    public void chooseTrue() {
                        //确定清除
                        mExitDialog.dismiss();
                        DataCleanManager.clearAllCache(getApplicationContext());
                        Toast.makeText(getApplicationContext(), "清除完成", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void chooseFalse() {
                        //取消
                        mExitDialog.dismiss();
                    }
                });
                mExitDialog.show();
            }
        });
        //退出账户
        findViewById(R.id.tuichuzhanghaoarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                final ExitDialog mExitDialog = new ExitDialog(SettingActivity.this);
                mExitDialog.setExitListener(new ExitDialog.ExitListener() {
                    @Override
                    public void chooseTrue() {
                        mExitDialog.dismiss();
                    }

                    @Override
                    public void chooseFalse() {


                        SharedPreferencesUtils.clearAll(getApplicationContext());
                        SharedPreferencesUtils.setDevice(getApplicationContext());
                        Intent intent = new Intent(SettingActivity.this, SplashActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
//                        setMsg();
                    }
                });
                mExitDialog.show();
                if ("".equals(UserBean.mobile)) {
                    mExitDialog.setContent2(UserBean.balance);
                } else {
                    mExitDialog.setContent(UserBean.balance);
                }
            }
        });
        //修改密码
        findViewById(R.id.xiugaimimaarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserBean.uid != 0) {
                    if ("".equals(UserBean.mobile)) {
                        Toast.makeText(getApplicationContext(), "请先绑定手机号", Toast.LENGTH_SHORT).show();
                    } else {
                        startActivity(new Intent(getApplicationContext(), ChangePsdActivity.class));
                    }
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                }
            }
        });
        View wx = findViewById(R.id.wx);
        if (UserBean.level > 1) {
            wx.setVisibility(View.VISIBLE);
            wx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(SettingActivity.this,MyWXActivity.class));
                }
            });
        }
        TextView version = findViewById(R.id.version);
        version.setText("V" + getVersionName(this));
        findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Beta.checkUpgrade();
            }
        });
        final TextView tvshouquan = findViewById(R.id.tvshouquan);
        if ("0".equals(UserBean.appopenid)) {
            tvshouquan.setText("未授权");
            findViewById(R.id.shouquan).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.show();
                    Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                    if (wechat.isAuthValid()) {
                        wechat.removeAccount(true);//执行此操作就可以移除掉本地授权状态和授权信息
                    }
                    if (!isInstallApp(SettingActivity.this, "com.tencent.mm")) {
                        Toast.makeText(SettingActivity.this, "微信未安装,请先安装微信", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    wechat.setPlatformActionListener(new PlatformActionListener() {
                        @Override
                        public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
//                            Log.i("____", platform.getDb().exportData());
                            final WxLoginBean loginBean = new Gson().fromJson(platform.getDb().exportData(), WxLoginBean.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    OkHttpDownloadJsonUtil.downloadJson(SettingActivity.this, Path.WXSHOUQUAN(UserBean.uid, loginBean.getOpenid()), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                                        @Override
                                        public void onsendJson(String json) {
//                                            Log.d("____", json);
                                            if (!"1".equals(json) && !"2".equals(json)) {
                                                try {
                                                    JSONObject object = new JSONObject(json);
                                                    if (object.optInt("status") == 1) {
                                                        tvshouquan.setText("已授权");
                                                        UserBean.appopenid = loginBean.getOpenid();
                                                        SharedPreferencesUtils.setParam(SettingActivity.this, "uid", UserBean.uid);
                                                        Toast.makeText(SettingActivity.this, object.optString("info"), Toast.LENGTH_SHORT).show();
                                                    } else {
                                                        Toast.makeText(SettingActivity.this, object.optString("info"), Toast.LENGTH_SHORT).show();
                                                    }
                                                    dialog.dismiss();
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                    Log.d("___", json);
                                                    dialog.dismiss();
                                                }
                                            } else {
                                                Toast.makeText(SettingActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                            }

                                        }
                                    });
                                }
                            });

                        }


                        @Override
                        public void onError(Platform platform, int i, Throwable throwable) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SettingActivity.this, "授权失败", Toast.LENGTH_SHORT).show();

                                }
                            });
                        }

                        @Override
                        public void onCancel(Platform platform, int i) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SettingActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                    wechat.showUser(null);

                }
            });
        } else {
            tvshouquan.setText("已授权");
        }
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在授权...Loading");
    }

    private ProgressDialog dialog;

    /**
     * @return 当前应用的版本号
     */
    public String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static boolean isInstallApp(Context context, String PACK_NAME) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName.toLowerCase(Locale.ENGLISH);
                if (pn.equals(PACK_NAME)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
